package com.mjp.learn.multi.task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者消费者模型
 * sychronized  wait notify 实现
 */
public class Test04 {

    // object 可以加锁
    public static final Object object = new Object();

    public static Integer MAX = 10;

    private static volatile Integer signal = 0;

    //生产方法
    public static void produce() {
        synchronized (object) {
            try {
                while (signal.equals(MAX)) {
                    object.wait();
                }
                signal++;
                Thread.sleep(100);

                System.out.println(Thread.currentThread().getName() + ":执行生产,仓库剩余:" + signal);
                object.notifyAll();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    //消费方法
    public static void consume() {
        synchronized (object) {
            try {
                while (signal.equals(0)) {
                    object.wait();
                }
                signal--;
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + ":执行消费, 仓库剩余:" + signal);
                object.notifyAll();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    Test04.consume();
                }
            }, "消费者" + i).start();
        }


        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 20; j++) {
                    Test04.produce();
                }
            }, "生产者" + i).start();
        }

    }
}
